package cocurrent;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：  共享锁和排他锁。  读锁占用时，当其他线程想要进入时，看其他线程的锁如果是一个读锁，则允许进入。可以极大提高并发读的效率
 */
public class ReadWriteLockTest {
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    static Lock readLock = lock.readLock();//读锁
    static Lock writeLock = lock.writeLock();//写锁

    public static void read(Lock lock) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(5);
            System.out.println("read over!!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock) {
        try {
            lock.lock();
            TimeUnit.SECONDS.sleep(5);
            System.out.println("write over!!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @Test
    public void test1() throws InterruptedException {
        Thread[] threads = new Thread[1000];
        for (int i = 0; i < 1000; i++) {
            if (i > 500 && i < 505) {
                threads[i] = new Thread(() -> write(writeLock));
            } else {
                threads[i] = new Thread(() -> read(readLock));
            }

        }
        for (int i = 0; i < 1000; i++) {
            threads[i].start();
        }
        for (int i = 0; i < 1000; i++) {
            threads[i].join();
        }


    }

}
